<template>
	<div class="app-department-personnel">
		<a-select
			:multiple="multiple"
			:transfer="true"
			transfer-class-name="app-department-personnel-select"
			:value="selectsLabel"
			:disabled="disabled || readonly"
			:clearable="true"
			:open="isOpen"
			@dropdownVisibleChange="onClick"
			@change="change"
		>
			<template #suffixIcon v-if="!disabled && !readonly">
				<SearchOutlined @click="openView" />
			</template>
			<a-select-option
				v-for="(item, index) in items"
				:key="index"
				:value="item.id"
			>
				{{ item.label }}
			</a-select-option>
		</a-select>
		<a-modal
			v-model:visible="openModal"
			:footer="null"
			centered
			destroyOnClose
			width="80%"
			:bodyStyle="{
				height: 'calc(100vh - 200px)',
				'justify-content': 'center',
			}"
		>
			<AppGroupSelect
				ref="groupSelectRef"
				:groupSelectParam="groupSelectParam"
				:groupSelectContext="groupSelectContext"
				@Change="groupSelect"
			></AppGroupSelect>
		</a-modal>
	</div>
</template>
<script setup lang="ts">
import { IEvent, IParam } from '@/core';
import { SearchOutlined } from '@ant-design/icons-vue';
import { Ref } from 'vue';
import { personnelSelectProps } from './department-personnel-select';
import { Http } from '@/http/http';
import { useAppStoreWithOut } from '@/store/modules/app';
import { useEditorTypeParams } from '@/hooks/use-editor';
interface EditorEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const props = defineProps(personnelSelectProps);
const emit = defineEmits<EditorEmit>();
// 类型校验
const { validateConfig } = useEditorTypeParams();
validateConfig();
let selects: any[] = []; //选中项对象集合
const selectsLabel: Ref<any[]> = ref([]); //选中项label集合
let items: Ref<any[]> = ref([]); //下拉数组
let filtervalue = ''; //过滤值
const isOpen = ref(false);
const openModal = ref(false);
let groupSelectParam = ref({});
let groupSelectContext = ref({});
const { getDeptPersonData, addDeptPersonData } = useAppStoreWithOut();

//下拉加载数据
const onClick = (open: boolean) => {
	if (open == true) {
		let tempUrl = '';
		if (props.treeurl) {
			tempUrl = props.treeurl.replace('{deptId}', filtervalue);
		}
		const personData: IParam[] | undefined = getDeptPersonData(
			'DepartmentPersonnel'
		);
		if (personData && personData.length > 0) {
			items.value = personData;
		} else {
			getDepertmentId();
			if (props.treeurl) {
				Http.getHttp()({
					method: props.requestMode,
					url: tempUrl,
					data: {},
				}).then((response: any) => {
					if (response && response.status === 200) {
						getTreeItems(response.data);
					}
				});
			} else {
				getPersonnelItems(filtervalue);
			}
		}
	}
};
//加载当前部门和其下级部门数据
const getTreeItems = (treeItems: any) => {
	if (treeItems.length > 0) {
		treeItems.forEach((treeItem: any) => {
			getPersonnelItems(treeItem.id);
		});
	}
};
//加载部门人员数据
const getPersonnelItems = (params: string) => {
	if (props.url) {
		let tempUrl = props.url.replace('{deptId}', params);
		Http.getHttp()({
			method: props.requestMode,
			url: tempUrl,
			data: {},
		})
			.then((response: any) => {
				if (response && response.status === 200) {
					items.value = response.data;
					addDeptPersonData('DepartmentPersonnel', items.value);
				}
			})
			.catch((error: any) => {
				console.error(
					error && error.message
						? error.message
						: App.ts('common.generic.requestexception', '请求异常')
				);
			});
	}
};

watch(
	() => props.data,
	(newVal: any, oldVal: any) => {
		selects = [];
		selectsLabel.value = [];
		if (newVal) {
			let item: any = {};
			item.label = [];
			item.id = [];
			if (props.name) {
				item.label = props.data[props.name]
					? props.data[props.name].split(',')
					: [];
			}
			if (props.valueItem) {
				item.id = props.data[props.valueItem]
					? props.data[props.valueItem].split(',')
					: [];
			}
			if (props.fillMap) {
				for (let key in props.fillMap) {
					if (props.fillMap[key]) {
						item[props.fillMap[key]] = props.data[key]
							? props.data[key].split(',')
							: [];
					}
				}
			}
			const callback: any = (item: any) => {
				item.label.forEach((val: string, index: number) => {
					let _item: any = {};
					for (let key in item) {
						_item[key] = item[key][index] ? item[key][index] : null;
					}
					selects.push(_item);
					let i = items.value.findIndex((select: any) =>
						Object.is(select.id, _item.id)
					);
					if (i < 0) {
						items.value.push(_item);
					}
					selectsLabel.value.push(_item.id);
				});
			};
			if (item.label.length == 0 && item.id.length > 0) {
				fillLabel(item, item.id, (result: any) => {
					item.label = result.label;
					callback(item);
				});
			} else {
				callback(item);
			}
			if (props.filter && newVal[props.filter]) {
				if (!filtervalue) {
					getDepertmentId();
				} else if (
					filtervalue &&
					!Object.is(newVal[props.filter], filtervalue)
				) {
					items.value = [];
					selects = [];
					selectsLabel.value = [];
					addDeptPersonData('DepartmentPersonnel', items.value);
				}
			}
		}
	},
	{
		immediate: true,
		deep: true,
	}
);
//填充label
const fillLabel = async (tempObject: any, valueItem: any, callback: any) => {
	if (
		tempObject.label.length === 0 &&
		valueItem.length > 0 &&
		props.codeListTag &&
		props.codeListType &&
		Object.is(props.codeListType, 'DYNAMIC')
	) {
		await App.getAppCodeListHelper()
			.getCodeListItems(props.codeListTag)
			.then((codeListResult: any) => {
				if (codeListResult.ok) {
					const result = codeListResult.data;
					if (result && result.length > 0 && valueItem.length > 0) {
						let tempLabel: Array<any> = [];
						valueItem.forEach((value: any) => {
							let temp_result: any = result.find((item: any) => {
								return item.id === value;
							});
							tempLabel.push(temp_result.label);
						});
						Object.assign(tempObject, { label: tempLabel });
					}
					callback(tempObject);
				}
			})
			.catch((error: any) => {
				console.warn(App.ts('common.generic.codenotexist', '代码表不存在'));
			});
	}
};
const change = (select: any) => {
	selects = [];
	if (props.multiple) {
		if (select.length > 0) {
			select.forEach((select: any) => {
				let index = items.value.findIndex((item) => Object.is(item.id, select));
				if (index >= 0) {
					selects.push(items.value[index]);
				}
			});
		}
	} else {
		let index = items.value.findIndex((item) => Object.is(item.id, select));
		if (index >= 0) {
			selects.push(items.value[index]);
		}
	}
	doEditorEmit();
};
const openView = (event: any) => {
	event.preventDefault();
	event.stopPropagation();
	const view: any = {
		codeName: 'AppGroupSelect',
		caption: App.ts('common.groupselect.groupselect', '分组选择'),
	};
	if (!view) {
		return;
	}
	const context: any = JSON.parse(JSON.stringify(props.context));
	getDepertmentId();
	const param: any = {};
	Object.assign(param, {
		showtree: props.treeurl ? true : false,
		url: props.url,
		treeurl: props.treeurl,
		filtervalue: filtervalue,
		multiple: props.multiple,
		selects: selects,
		selectType: 'dept',
		requestMode: props.requestMode,
	});
	if (props.context) {
		groupSelectContext.value = context;
		groupSelectParam.value = param;
		openModal.value = true;
	}
};

const groupSelect = (data: IParam[]) => {
	openModal.value = false;
	items.value = [];
	if (data && data.length > 0) {
		items.value = data;
	}
	doEditorEmit();
};

// 编辑器抛值
const doEditorEmit = (): any => {
	let item: any = {};
	if (props.name) {
		item[props.name] = null;
	}
	if (props.valueItem) {
		item[props.valueItem] = null;
	}
	if (props.fillMap) {
		for (let key in props.fillMap) {
			item[key] = null;
		}
	}
	if (props.multiple) {
		selects.forEach((select: any) => {
			if (props.name) {
				item[props.name] = item[props.name]
					? `${item[props.name]},${select.label}`
					: select.label;
			}
			if (props.valueItem) {
				item[props.valueItem] = item[props.valueItem]
					? `${item[props.valueItem]},${select.id}`
					: select.id;
			}
			if (props.fillMap) {
				for (let key in props.fillMap) {
					item[key] = item[key]
						? `${item[key]},${select[props.fillMap[key]]}`
						: select[props.fillMap[key]];
				}
			}
		});
	} else {
		if (props.name) {
			item[props.name] = selects.length > 0 ? selects[0].label : null;
		}
		if (props.valueItem) {
			item[props.valueItem] = selects.length > 0 ? selects[0].id : null;
		}
		if (props.fillMap) {
			for (let key in props.fillMap) {
				item[key] = selects.length > 0 ? selects[0][props.fillMap[key]] : null;
			}
		}
	}
	emit('component-action', {
		name: `${props.name}`,
		action: 'valueChang',
		data: item.label || item[props.name!],
	});
	if (props.valueItem) {
		emit('component-action', {
			name: `${props.valueItem}`,
			action: 'valueChang',
			data: item.id || item[props.valueItem],
		});
	}
};

//获取需要过滤的部门ID
const getDepertmentId = () => {
	const context: any = JSON.parse(JSON.stringify(props.context));
	if (props.filter) {
		if (props.data[props.filter]) {
			filtervalue = props.data[props.filter];
		} else if (context[props.filter]) {
			filtervalue = context[props.filter];
		} else {
			filtervalue = context.srfsdept;
		}
	} else {
		filtervalue = context.srfsdept;
	}
};
</script>
